package io.renren.common.utils.dingtalk;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceListRequest;
import com.dingtalk.api.request.OapiCallBackRegisterCallBackRequest;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiProcessinstanceGetRequest;
import com.dingtalk.api.request.OapiUserGetDeptMemberRequest;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.response.OapiAttendanceListResponse;
import com.dingtalk.api.response.OapiCallBackRegisterCallBackResponse;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiProcessinstanceGetResponse;
import com.dingtalk.api.response.OapiUserGetDeptMemberResponse;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.taobao.api.ApiException;

import io.renren.common.utils.DateUtils;

/**
 * 钉钉开发平台   
 * @author Administrator
 *
 */
public class DingtalkUtils {
	public static String APP_KEY = "dingrn0qccfnfg58u09x";
	public static String APP_SECRET = "TZ0eCT7z13CDFlsmubTS_eBZ5wl6dtXZXEUAKCHMABb9HZBwWUUmZlhsmXZG51VO";
	
	public static void main(String[] args) throws ApiException {
		
		Long time = 1546574764000l;
		Long oneDay = 1000 * 60 * 60 * 24l;
		System.out.println(time % oneDay);
		
		
		time = 1547899891000l;
		System.out.println(time % oneDay);
		
		time = 1547912071000l;
		System.out.println(time % oneDay);
		
		//1547899891000
		
		//1547912071000
		/*String accessToken = "bf8c15b526d5371fb80b8b9361895b80";
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
		Date startTime = DateUtils.getStartTime(new Date(), -1);  //获取月份第一天
		int monthDays = DateUtils.getDayOfMonth(startTime);
		int weeks = monthDays / 7;
		int days = monthDays % 7;
		
		System.out.println("本月"+monthDays + "天," + weeks + "周,剩余" + days+"天");
		Long oneDay = 1000 * 60 * 60 * 24l;
		long start = startTime.getTime();
		String[] uids = {"152608142236526592","116812103730946460","116812103730946460","1202180815765191","193436415221650092","172936334126639687","04131240368472","230068134929324732","192616591829793791","025837613587"};
		for (int i = 1; i <= weeks; i++) {
			System.out.print(DateUtils.getStartTimeString(new Date(start)));
			System.out.print("====");
			System.out.println(DateUtils.getEndTimeString(new Date(start+(oneDay*6))));
			System.out.println(attendanceList(accessToken,DateUtils.getStartTimeString(new Date(start)), DateUtils.getEndTimeString(new Date(start+(oneDay*6))), Arrays.asList(uids)));
			start = new Date(start+(oneDay*7)).getTime();
		}
		if(days > 0){
			System.out.print(DateUtils.getStartTimeString(new Date(start)));
			System.out.print("====");
			System.out.println(DateUtils.getEndTimeString(new Date(start+(oneDay*(days - 1)))));
			System.out.println(attendanceList(accessToken,DateUtils.getStartTimeString(new Date(start)), DateUtils.getEndTimeString(new Date(start+(oneDay*(days - 1)))), Arrays.asList(uids)));
		}
		*/
		
		
        
        
        
       
        /*while (s <= e) {
        	start = new Date(s);
        	start = new Date(s);
        	//System.out.println(DateUtils.format(start, DateUtils.DATE_TIME_PATTERN));
            s += oneDay;
            //String[] uids = {"152608142236526592","116812103730946460","116812103730946460","1202180815765191","193436415221650092","172936334126639687","04131240368472","230068134929324732","192616591829793791","025837613587"};
            //System.out.println(attendanceList(accessToken,DateUtils.format(DateUtils.getStartTime(start), DateUtils.DATE_TIME_PATTERN), DateUtils.format(DateUtils.getEndTime(start), DateUtils.DATE_TIME_PATTERN), Arrays.asList(uids)));
        }*/

		
		
//		
//		

		
	}
	

	
	/**
	 * 获取access_token(开发者在调用钉钉的服务端API之前，需要先获取access_token。)
	 * @param appKey
	 * @param appSecret
	 * @return
	 * @throws ApiException
	 */
	public static String getAccessToken(String appKey,String appSecret){
		DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
		OapiGettokenRequest request = new OapiGettokenRequest();
		request.setAppkey(appKey);
		request.setAppsecret(appSecret);
		request.setHttpMethod("GET");
		OapiGettokenResponse response;
		try {
			response = client.execute(request);
			return response.getBody();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}
	
	/**
	 * 获取部门用户userid列表（推荐使用）
	 * @param appKey
	 * @param appSecret
	 * @return
	 * @throws ApiException
	 */
	public static String getDeptMember(String accessToken,String deptId){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
		OapiUserGetDeptMemberRequest req = new OapiUserGetDeptMemberRequest();
		req.setDeptId(deptId);
		req.setHttpMethod("GET");
		OapiUserGetDeptMemberResponse rsp;
		try {
			rsp = client.execute(req, accessToken);
			return rsp.getBody();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 获取用户详情
	 * @param accessToken
	 * @param userid
	 * @return
	 * @throws ApiException
	 */
	public static String getMember(String accessToken,String userid){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
		OapiUserGetRequest request = new OapiUserGetRequest();
		request.setUserid(userid);
		request.setHttpMethod("GET");
		OapiUserGetResponse response;
		try {
			response = client.execute(request, accessToken);
			return response.getBody();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 获取打卡列表
	 * @param accessToken
	 * @param userid
	 * @return
	 */
	public static String attendanceList(String accessToken,List<String> userids){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
		OapiAttendanceListRequest request = new OapiAttendanceListRequest();
		request.setWorkDateFrom(DateUtils.format(DateUtils.getStartTime(), DateUtils.DATE_TIME_PATTERN));
		request.setWorkDateTo(DateUtils.format(DateUtils.getStartTime(DateUtils.addDateDays(new Date(), 1)), DateUtils.DATE_TIME_PATTERN));
		request.setUserIdList(userids);
		request.setOffset(0L);
		request.setLimit(50L);
		
		try {
			OapiAttendanceListResponse response = client.execute(request,accessToken);
			response = client.execute(request, accessToken);
			return response.getBody();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public static String attendanceList(String accessToken,String startTime,String endTime,List<String> userids,Long pageNo,Long pageSize){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
		OapiAttendanceListRequest request = new OapiAttendanceListRequest();
		request.setWorkDateFrom(startTime);
		request.setWorkDateTo(endTime);
		request.setUserIdList(userids);
		request.setOffset((pageNo - 1) * pageSize);
		request.setLimit(pageSize);
		
		try {
			OapiAttendanceListResponse response = client.execute(request,accessToken);
			response = client.execute(request, accessToken);
			return response.getBody();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 获取单个审批实例
	 * @param accessToken
	 * @param userids
	 * @return
	 */
	public static String processinstance(String accessToken,String processInstanceId){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
		OapiProcessinstanceGetRequest request = new OapiProcessinstanceGetRequest();
		request.setProcessInstanceId(processInstanceId);
		try {
			OapiProcessinstanceGetResponse response = client.execute(request,accessToken);
			return response.getBody();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 注册业务事件回调接口
	 * @param accessToken
	 * @param processInstanceId
	 * @return
	 */
	public static String registerCallBack(String accessToken,String token,String aesKey,String url){
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/call_back/register_call_back");
		OapiCallBackRegisterCallBackRequest request = new OapiCallBackRegisterCallBackRequest();
		request.setUrl(url);
		request.setAesKey(aesKey);
		request.setToken(token);
		request.setCallBackTag(Arrays.asList("bpms_instance_change", "bpms_instance_change"));
		
		try {
			
			OapiCallBackRegisterCallBackResponse response = client.execute(request,accessToken);
			System.out.println(response.getBody());
			return response.getBody();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * 发送钉钉文本消息
	 * @param accessToken
	 * @param useridList
	 * @param content
	 * @return
	 */
	public static String sendText(String accessToken,String names,String userids,String content){
		//String accessToken = "bf8c15b526d5371fb80b8b9361895b80";
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");

		OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
		request.setUseridList(userids);
		request.setAgentId(197622408L);
		request.setToAllUser(false);

		OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
		msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
		msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
		msg.getOa().getHead().setText("head");
		msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
		msg.getOa().getBody().setContent(content);
		msg.getOa().getBody().setAuthor(names);
		msg.setMsgtype("oa");
		request.setMsg(msg);
		try {
			OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request,accessToken);
			System.out.println(response.getBody());
			return response.getBody();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	
	
	
	
}
